package com.example.srb.service2oss.controller.api;

import com.example.srb.common.exception.BusinessException;
import com.example.srb.common.result.ResponseEnum;
import com.example.srb.common.result.Result;
import com.example.srb.service2oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/api/oss/file")
//@CrossOrigin
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@ApiParam(value = "文件",required = true)@RequestParam("file")
                                     MultipartFile multipartFile,
                         @ApiParam(value = "模块",required = true)@RequestParam("module") String module){
        try {
            InputStream inputStream = multipartFile.getInputStream();
            String originalFilename = multipartFile.getOriginalFilename();
            String url = fileService.upload(inputStream,module,originalFilename);
            return Result.ok().data("url",url);
        }catch (IOException e){
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }

    }

    @ApiOperation("文件删除")
    @DeleteMapping("/remove")
    public Result remove(@RequestParam("url") @ApiParam(value = "需要删除的文件路径",required = true) String url){
        fileService.remove(url);
        return Result.ok().message("文件删除成功!");
    }
}
